<template>
  <div class="admin-page admin-major-level">
    <!-- 培养层次管理 -->
    <TrainingLevelManagement
      :data="filteredCengCi"
      :filters="cengciFilters"
      :loading="cengciLoading"
      :total="cengciTotal"
      :page-size="cengciPageSize"
      :current-page="cengciCurrentPage"
      @add="openCengCiDialog(null)"
      @edit="openCengCiDialog"
      @delete="deleteCengCi"
      @search="searchCengCi"
      @reset="resetCengciFilters"
      @page-change="handleCengciPageChange"
    />

    <!-- 专业管理 -->
    <MajorManagement
      :data="filteredMajors"
      :departments="departments"
      :filters="majorFilters"
      :loading="majorLoading"
      :total="majorTotal"
      :page-size="majorPageSize"
      :current-page="majorCurrentPage"
      @add="openMajorDialog(null)"
      @edit="openMajorDialog"
      @delete="deleteMajor"
      @search="searchMajors"
      @reset="resetMajorFilters"
      @page-change="handleMajorPageChange"
    />
    
    <!-- 培养层次编辑对话框 -->
    <TrainingLevelDialog
      v-model="cengciDialogVisible"
      :form-data="cengCiForm"
      :submitting="cengciSubmitting"
      @submit="submitCengCiForm"
      @cancel="cengciDialogVisible = false"
    />

    <!-- 专业编辑对话框 -->
    <MajorDialog
      v-model="majorDialogVisible"
      :form-data="majorForm"
      :departments="departments"
      :submitting="majorSubmitting"
      @submit="submitMajorForm"
      @cancel="majorDialogVisible = false"
    />
  </div>
</template>

<script>
import { ref, onMounted, computed, reactive, nextTick } from 'vue';
import { cengCiApi, majorApi, departmentApi } from '@/api/base-data';
import { ElMessage, ElMessageBox } from 'element-plus';
import TrainingLevelManagement from '@/components/major/TrainingLevelPanel.vue';
import MajorManagement from '@/components/major/MajorManagePanel.vue';
import TrainingLevelDialog from '@/components/major/TrainingLevelDialog.vue';
import MajorDialog from '@/components/major/MajorEditDialog.vue';

export default {
  components: {
    TrainingLevelManagement,
    MajorManagement,
    TrainingLevelDialog,
    MajorDialog
  },
  setup() {
    // 培养层次相关状态
    const cengCiList = ref([]);
    const cengciLoading = ref(false);
    const cengciSubmitting = ref(false);
    const cengciDialogVisible = ref(false);
    const cengciCurrentPage = ref(1);
    const cengciPageSize = ref(10);
    const cengciTotal = ref(0);
    
    const cengciFilters = reactive({
      name: ''
    });
    
    const cengCiForm = reactive({
      id: null,
      name: ''
    });

    // 专业相关状态
    const majors = ref([]);
    const departments = ref([]);
    const majorLoading = ref(false);
    const majorSubmitting = ref(false);
    const majorDialogVisible = ref(false);
    const majorCurrentPage = ref(1);
    const majorPageSize = ref(10);
    const majorTotal = ref(0);
    
    const majorFilters = reactive({
      name: '',
      departmentId: ''
    });
    
    const majorForm = reactive({
      id: '',
      name: '',
      code: '',
      departmentId: '',
      description: ''
    });

    // 培养层次方法
    const fetchCengCi = async () => {
      cengciLoading.value = true;
      try {
        cengCiList.value = await cengCiApi.getAllCengCi();
        cengciTotal.value = cengCiList.value.length;
      } catch (error) {
        console.error('获取培养层次列表失败:', error);
        ElMessage.error('获取培养层次列表失败');
      } finally {
        cengciLoading.value = false;
      }
    };
    
    const filteredCengCi = computed(() => {
      let filtered = cengCiList.value;
      
      if (cengciFilters.name) {
        filtered = filtered.filter(item => 
          item.name.includes(cengciFilters.name)
        );
      }
      
      cengciTotal.value = filtered.length;
      const startIndex = (cengciCurrentPage.value - 1) * cengciPageSize.value;
      return filtered.slice(startIndex, startIndex + cengciPageSize.value);
    });
    
    const searchCengCi = () => {
      cengciCurrentPage.value = 1;
    };
    
    const resetCengciFilters = () => {
      cengciFilters.name = '';
      cengciCurrentPage.value = 1;
    };
    
    const handleCengciPageChange = (page) => {
      cengciCurrentPage.value = page;
    };
    
    // 强制重置培养层次表单
    const forceResetCengCiForm = () => {
      cengCiForm.id = null;
      cengCiForm.name = '';
    };
    
    const openCengCiDialog = async (cengCi) => {
      // 总是先强制重置表单
      forceResetCengCiForm();
      
      if (cengCi) {
        // 编辑模式：填充现有数据
        cengCiForm.id = cengCi.id;
        cengCiForm.name = cengCi.name;
      }
      
      cengciDialogVisible.value = true;
    };
    
    const submitCengCiForm = async (formData) => {
      try {
        cengciSubmitting.value = true;
        
        if (formData.id) {
          await cengCiApi.updateCengCi(formData.id, formData);
          ElMessage.success('更新培养层次成功');
        } else {
          await cengCiApi.createCengCi(formData);
          ElMessage.success('创建培养层次成功');
        }
        
        cengciDialogVisible.value = false;
        fetchCengCi();
      } catch (error) {
        console.error('提交培养层次表单失败:', error);
        ElMessage.error('操作失败');
      } finally {
        cengciSubmitting.value = false;
      }
    };

    const deleteCengCi = async (cengCi) => {
      try {
        await ElMessageBox.confirm(`确定要删除培养层次 ${cengCi.name} 吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await cengCiApi.deleteCengCi(cengCi.id);
        ElMessage.success('删除成功');
        fetchCengCi();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除培养层次失败:', error);
          ElMessage.error(`删除培养层次失败: ${error.message || '未知错误'}`);
        }
      }
    };

    // 专业方法
    const fetchMajors = async () => {
      majorLoading.value = true;
      try {
        majors.value = await majorApi.getAllMajors();
        majorTotal.value = majors.value.length;
      } catch (error) {
        console.error('获取专业列表失败:', error);
        ElMessage.error('获取专业列表失败');
      } finally {
        majorLoading.value = false;
      }
    };
    
    const fetchDepartments = async () => {
      try {
        departments.value = await departmentApi.getAllDepartments();
      } catch (error) {
        console.error('获取部门列表失败:', error);
        ElMessage.error('获取部门列表失败');
      }
    };
    
    const filteredMajors = computed(() => {
      let filtered = majors.value;
      
      if (majorFilters.name) {
        filtered = filtered.filter(major => 
          major.name.includes(majorFilters.name)
        );
      }
      
      if (majorFilters.departmentId) {
        filtered = filtered.filter(major => 
          major.departmentId === majorFilters.departmentId
        );
      }
      
      majorTotal.value = filtered.length;
      const startIndex = (majorCurrentPage.value - 1) * majorPageSize.value;
      return filtered.slice(startIndex, startIndex + majorPageSize.value);
    });
    
    const searchMajors = () => {
      majorCurrentPage.value = 1;
    };
    
    const resetMajorFilters = () => {
      majorFilters.name = '';
      majorFilters.departmentId = '';
      majorCurrentPage.value = 1;
    };
    
    const handleMajorPageChange = (page) => {
      majorCurrentPage.value = page;
    };
    
    // 强制重置专业表单
    const forceResetMajorForm = () => {
      majorForm.id = '';
      majorForm.name = '';
      majorForm.code = '';
      majorForm.departmentId = '';
      majorForm.description = '';
    };
    
    const openMajorDialog = async (major) => {
      // 总是先强制重置表单
      forceResetMajorForm();
      
      if (major) {
        // 编辑模式：填充现有数据
        majorForm.id = major.id;
        majorForm.name = major.name;
        majorForm.code = major.code;
        majorForm.departmentId = major.departmentId;
        majorForm.description = major.description || '';
      }
      
      majorDialogVisible.value = true;
    };
    
    const submitMajorForm = async (formData) => {
      try {
        majorSubmitting.value = true;
        
        if (formData.id) {
          await majorApi.updateMajor(formData.id, formData);
          ElMessage.success('更新专业成功');
        } else {
          await majorApi.createMajor(formData);
          ElMessage.success('创建专业成功');
        }
        
        majorDialogVisible.value = false;
        fetchMajors();
      } catch (error) {
        console.error('提交专业表单失败:', error);
        ElMessage.error('操作失败');
      } finally {
        majorSubmitting.value = false;
      }
    };

    const deleteMajor = async (major) => {
      try {
        await ElMessageBox.confirm(`确定要删除专业 ${major.name} 吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await majorApi.deleteMajor(major.id);
        ElMessage.success('删除成功');
        fetchMajors();
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除专业失败:', error);
          ElMessage.error(`删除专业失败: ${error.message || '未知错误'}`);
        }
      }
    };

    onMounted(() => {
      fetchCengCi();
      fetchMajors();
      fetchDepartments();
    });

    return {
      // 培养层次
      filteredCengCi,
      cengciLoading,
      cengciFilters,
      cengciCurrentPage,
      cengciPageSize,
      cengciTotal,
      cengCiForm,
      cengciDialogVisible,
      cengciSubmitting,
      searchCengCi,
      resetCengciFilters,
      handleCengciPageChange,
      openCengCiDialog,
      submitCengCiForm,
      deleteCengCi,
      forceResetCengCiForm,
      
      // 专业
      filteredMajors,
      departments,
      majorLoading,
      majorFilters,
      majorCurrentPage,
      majorPageSize,
      majorTotal,
      majorForm,
      majorDialogVisible,
      majorSubmitting,
      searchMajors,
      resetMajorFilters,
      handleMajorPageChange,
      openMajorDialog,
      submitMajorForm,
      deleteMajor,
      forceResetMajorForm
    };
  }
};
</script>

<style scoped>
.admin-major-level {
  padding: 0;
}
</style>